﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Text.RegularExpressions;

using DEFUSE;

namespace auxiliary_proj
{
    public partial class FormCreateUser : Form
    {
        Parser p;
        byte[] image_arr;
        public FormCreateUser()
        {
            InitializeComponent();
            tbUserFirstName.Focus();
            p = new Parser();
            tbPassword2.Enabled = false;
        }
        //variables declaration
        public static string fname, lname, username, password, retypePass, email;
        public static int admin;
        bool isFirstName = false, isLastName = false, isUserName = false, isPass = false, isRetype = false, isEmail = false;

        //server connection stuff
        private static MySqlConnection conn;
        private static MySqlCommand comm;        
        MemoryStream ms;       

        private void FormCreateUser_Load(object sender, EventArgs e)
        {
            //parse the server file
            Program.parseServerInfo();

            //establish a connection to the server.
            conn = new MySqlConnection(Program.getConnection());
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            PictureBox p = sender as PictureBox;
            if (p != null)
            {
                //file open dialog box
                OpenFileDialog ofd = new OpenFileDialog();
                //Filter images in the open file dialog
                ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {   
                    //display the image on the picture box
                    p.Image = Image.FromFile(ofd.FileName);
                    p.SizeMode = PictureBoxSizeMode.StretchImage;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void UserBtnSubmit_Click(object sender, EventArgs e)
        {
            fname = tbUserFirstName.Text;
            lname = tbUserLastName.Text;
            username = tbUserName.Text;
            //hash the password
            password = PasswordHash.HashPassword(tbPassword.Text);
            retypePass = tbPassword2.Text;
            email = tbUserEmail.Text;
            admin = (PermissionLevelCheckBox.Checked) ? 2 : 1;

            if (EmpPicBox.Image != null)
            {
                if ((fname != "") && (lname != "") && (username != "") && (password != "") && (retypePass != "") && (email != ""))
                {
                    if (isUserName)
                    {
                        if (isPass)
                        {
                            if (isRetype)
                            {
                                if (isEmail)
                                {
                                    //parse the server file
                                    Program.parseServerInfo();

                                    //establish a connection to the server.
                                    conn = new MySqlConnection(Program.getConnection());

                                    convert_photo();
                                    //insert query
                                    string insert = "INSERT INTO `USER`(`first_name`, `last_name`, `user_name`, `password`, `access_lvl`, `email`, `photo`) VALUES ('" + fname + "','" + lname + "', '" + username + "', '" + password + "', '" + admin + "', '" + email + "', @photo)";
                                    
                                    comm = new MySqlCommand(insert, conn);
                                    comm.Parameters.AddWithValue("@photo", image_arr);

                                    Cursor.Current = Cursors.WaitCursor;
                                    try
                                    {
                                        conn.Open();
                                        try
                                        {
                                            //Write image to the database
                                            int record = comm.ExecuteNonQuery();
                                            if (record > 0)
                                            {
                                                MessageBox.Show("User Created!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);                                            
                                            }
                                            else
                                                MessageBox.Show("Failed to Create User!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                        catch (MySqlException ex)
                                        {
                                            MessageBox.Show(ex.Message);
                                        }
                                    }
                                    catch (DataException ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                    finally
                                    {
                                        conn.Close();
                                    }
                                    Cursor.Current = Cursors.Default;
                                    this.Close();
                                }
                                else MessageBox.Show("Invalid Email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else MessageBox.Show("Password does not match!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else MessageBox.Show("Invalid Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else MessageBox.Show("Invalid Username", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                else MessageBox.Show("Invalid Entry (*Missing Field(s))", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else MessageBox.Show("Profile Image Missing!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        public void convert_photo()
        {
            if (EmpPicBox != null)
            {
                ms = new MemoryStream();
                EmpPicBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);               
                image_arr = ms.ToArray();            
            }
        }

        private void firstName_textChanged(object sender, EventArgs e)
        {
            isFirstName = Parser.isMatch(sender, @"^[a-zA-Z]{1,15}$");
        }

        private void lastName_textChanged(object sender, EventArgs e)
        {
            isLastName = Parser.isMatch(sender, @"^[a-zA-Z]{1,20}$");
        }

        private void userName_textChanged(object sender, EventArgs e)
        {
            isUserName = Parser.isMatch(sender, @"^(?=.{3,15}$)([A-Za-z0-9][._()\[\]-]?)*$");
        }

        private void password_textChanged(object sender, EventArgs e)
        {
            isPass = Parser.isMatch(sender, @"^[a-zA-Z][\w!@#$%^&*\(\)-+';:<>`~]{3,15}$");

            if (isPass)
            {
                tbPassword2.Enabled = true;
                if (tbPassword2.Text.Equals(""))
                    tbPassword2.BackColor = SystemColors.Info;
                else
                {
                    //run regex when text changes. if invalid, make textbox red, if valid make green
                    //this pattern is any alpha-numeric value with length between 4 and 10
                    isRetype = tbPassword2.Text.Equals(tbPassword.Text) ? true : false;

                    if (isRetype)
                        //make a greenish color
                        tbPassword2.BackColor = System.Drawing.ColorTranslator.FromHtml("#B9FF94");
                    else
                        //make a redish color
                        tbPassword2.BackColor = System.Drawing.ColorTranslator.FromHtml("#FF7D5D");
                }
            }
            else
            {
                tbPassword2.Enabled = false;
                tbPassword2.BackColor = SystemColors.Info;
            }
        }

        private void retypePass_textChanged(object sender, EventArgs e)
        {
            //only test if password is valid
            if (isPass)
            {
                if (((TextBox)sender).Text.Equals(""))
                    ((TextBox)sender).BackColor = SystemColors.Info;
                else
                {
                    //run regex when text changes. if invalid, make textbox red, if valid make green
                    //this pattern is any alpha-numeric value with length between 4 and 10
                    isRetype = ((TextBox)sender).Text.Equals(tbPassword.Text) ? true : false;

                    if (isRetype)
                        //make a greenish color
                        ((TextBox)sender).BackColor = System.Drawing.ColorTranslator.FromHtml("#B9FF94");
                    else
                        //make a redish color
                        ((TextBox)sender).BackColor = System.Drawing.ColorTranslator.FromHtml("#FF7D5D");
                }
            }
        }

        private void email_textChanged(object sender, EventArgs e)
        {
            isEmail = Parser.isMatch(sender, @"\w+@\w+\.+\w{2,}");
        }
    }
}

